<template>
  <div class="friend-links-container">
    <!-- 顶部标题区域 -->
    <div class="header">
      <h1 class="title">友情链接管理</h1>
      <p class="subtitle">管理您的网站友情链接</p>
    </div>
    
    <!-- 操作控制区域 -->
    <div class="control-panel">
      <el-button 
        type="primary" 
        class="add-btn"
        @click="openDialog('create')"
      >
        <el-icon><Plus /></el-icon>
        <span>添加链接</span>
      </el-button>
      
      <el-input 
        v-model="searchQuery"
        placeholder="搜索链接..."
        class="search-input"
        clearable
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </div>
    
    <!-- 链接列表区域 -->
    <div class="links-container">
      <el-table 
        :data="filteredLinks" 
        style="width: 100%"
        row-key="id"
        stripe
        border
      >
        <el-table-column prop="name" label="网站名称" width="180">
          <template #default="{ row }">
            <div class="link-name">
              <el-avatar :src="row.logo" shape="square" size="small" />
              <span>{{ row.name }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="url" label="网站地址">
          <template #default="{ row }">
            <a :href="row.url" target="_blank" class="link-url">{{ row.url }}</a>
          </template>
        </el-table-column>
        
        <el-table-column prop="description" label="描述" width="250" />
        
        <el-table-column prop="sortOrder" label="排序" width="200">
          <template #default="{ row }">
            <el-input-number 
              v-model="row.sortOrder" 
              :min="1" 
              :max="100" 
              size="small"
              @change="updateSortOrder(row)"
            />
          </template>
        </el-table-column>
        
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status ? 'success' : 'danger'">
              {{ row.status ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <!-- 操作列优化 - 按钮在同一行 -->
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button 
                size="small" 
                type="primary"
                @click="openDialog('edit', row)"
                class="action-btn"
              >
                <el-icon><Edit /></el-icon>
                <span>编辑</span>
              </el-button>
              <el-button 
                size="small" 
                type="danger"
                @click="deleteLink(row.id)"
                class="action-btn"
              >
                <el-icon><Delete /></el-icon>
                <span>删除</span>
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 空状态 -->
      <div v-if="filteredLinks.length === 0" class="empty-state">
        <el-empty description="暂无友情链接" />
        <el-button 
          type="primary" 
          class="add-btn"
          @click="openDialog('create')"
        >
          <el-icon><Plus /></el-icon>
          <span>添加链接</span>
        </el-button>
      </div>
    </div>
    
    <!-- 添加/编辑链接弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
    >
      <el-form :model="form" label-width="100px" label-position="left">
        <el-form-item label="网站名称" required>
          <el-input 
            v-model="form.name" 
            placeholder="输入网站名称"
          />
        </el-form-item>
        
        <el-form-item label="网站地址" required>
          <el-input 
            v-model="form.url" 
            placeholder="输入网站URL"
            type="url"
          >
            <template #prepend>https://</template>
          </el-input>
        </el-form-item>
        
        <el-form-item label="网站Logo">
          <div class="logo-upload">
            <div 
              class="logo-preview"
              :style="{ backgroundImage: `url(${form.logo})` }"
            >
              <div v-if="!form.logo" class="logo-placeholder">
                <el-icon><Picture /></el-icon>
                <span>上传Logo</span>
              </div>
            </div>
            <el-button 
              type="primary" 
              @click="triggerLogoUpload"
              class="upload-btn"
            >
              <el-icon><Upload /></el-icon>
              <span>选择图片</span>
            </el-button>
            <input 
              type="file" 
              ref="logoInput" 
              accept="image/*" 
              @change="handleLogoUpload"
              class="file-input"
            />
          </div>
        </el-form-item>
        
        <el-form-item label="网站描述">
          <el-input 
            v-model="form.description" 
            type="textarea"
            placeholder="输入网站描述"
            :rows="3"
          />
        </el-form-item>
        
        <el-form-item label="排序值">
          <el-input-number 
            v-model="form.sortOrder" 
            :min="1" 
            :max="100" 
          />
        </el-form-item>
        
        <el-form-item label="状态">
          <el-switch 
            v-model="form.status" 
            active-text="启用" 
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { 
  Plus, Search, Edit, Delete, 
  Picture, Upload 
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 友情链接数据结构
const friendLinks = ref([
  {
    id: 1,
    name: 'Element Plus',
    url: 'https://element-plus.org',
    logo: 'https://element-plus.org/images/element-plus-logo.svg',
    description: '一套为开发者、设计师和产品经理准备的基于 Vue 3 的桌面端组件库',
    sortOrder: 1,
    status: true
  },
  {
    id: 2,
    name: 'Vue.js',
    url: 'https://vuejs.org',
    logo: 'https://vuejs.org/images/logo.png',
    description: '渐进式 JavaScript 框架',
    sortOrder: 2,
    status: true
  },
  {
    id: 3,
    name: 'GitHub',
    url: 'https://github.com',
    logo: 'https://github.githubassets.com/images/modules/logos_page/GitHub-Mark.png',
    description: '全球最大的代码托管平台',
    sortOrder: 3,
    status: true
  },
  {
    id: 4,
    name: 'MDN Web Docs',
    url: 'https://developer.mozilla.org',
    logo: 'https://developer.mozilla.org/favicon-48x48.cbbd161b.png',
    description: 'Web 开发技术文档',
    sortOrder: 4,
    status: true
  },
  {
    id: 5,
    name: 'Stack Overflow',
    url: 'https://stackoverflow.com',
    logo: 'https://cdn.sstatic.net/Sites/stackoverflow/Img/favicon.ico?v=ec617d715196',
    description: '程序员问答社区',
    sortOrder: 5,
    status: true
  }
])

// 搜索查询
const searchQuery = ref('')

// 过滤后的链接列表
const filteredLinks = computed(() => {
  if (!searchQuery.value) return friendLinks.value
  const query = searchQuery.value.toLowerCase()
  return friendLinks.value.filter(link => 
    link.name.toLowerCase().includes(query) || 
    link.url.toLowerCase().includes(query) ||
    (link.description && link.description.toLowerCase().includes(query))
  )
})

// 弹窗状态
const dialogVisible = ref(false)
const dialogMode = ref('create') // 'create' 或 'edit'
const currentLinkId = ref(null)

// 表单数据
const form = reactive({
  name: '',
  url: '',
  logo: '',
  description: '',
  sortOrder: 1,
  status: true
})

// 弹窗标题
const dialogTitle = computed(() => {
  return dialogMode.value === 'create' ? '添加友情链接' : '编辑友情链接'
})

// Logo上传相关
const logoInput = ref(null)

// 打开弹窗
function openDialog(mode, link = null) {
  dialogMode.value = mode
  
  if (mode === 'edit' && link) {
    currentLinkId.value = link.id
    Object.assign(form, link)
  } else {
    // 重置表单
    Object.assign(form, {
      name: '',
      url: '',
      logo: '',
      description: '',
      sortOrder: friendLinks.value.length + 1,
      status: true
    })
  }
  
  dialogVisible.value = true
}

// 触发Logo上传
function triggerLogoUpload() {
  if (logoInput.value) {
    logoInput.value.click()
  }
}

// 处理Logo上传
function handleLogoUpload(event) {
  const input = event.target
  if (input.files && input.files[0]) {
    const file = input.files[0]
    const reader = new FileReader()
    
    reader.onload = (e) => {
      if (e.target?.result) {
        form.logo = e.target.result
      }
    }
    
    reader.readAsDataURL(file)
  }
}

// 表单提交
function handleSubmit() {
  if (!form.name.trim()) {
    ElMessage.warning('请输入网站名称')
    return
  }
  
  if (!form.url.trim()) {
    ElMessage.warning('请输入网站地址')
    return
  }
  
  // 验证URL格式
  try {
    new URL(form.url)
  } catch (e) {
    ElMessage.warning('请输入有效的URL地址')
    return
  }
  
  if (dialogMode.value === 'create') {
    // 添加新链接
    const newLink = {
      id: Date.now(),
      ...form
    }
    friendLinks.value.push(newLink)
    ElMessage.success('链接添加成功')
  } else if (currentLinkId.value) {
    // 更新现有链接
    const index = friendLinks.value.findIndex(link => link.id === currentLinkId.value)
    if (index !== -1) {
      Object.assign(friendLinks.value[index], form)
      ElMessage.success('链接更新成功')
    }
  }
  
  dialogVisible.value = false
}

// 删除链接
function deleteLink(id) {
  ElMessageBox.confirm('确定要删除这个友情链接吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    friendLinks.value = friendLinks.value.filter(link => link.id !== id)
    ElMessage.success('链接已删除')
  }).catch(() => {
    // 用户取消操作
  })
}

// 更新排序
function updateSortOrder(link) {
  // 在实际应用中，这里应该发送请求到后端更新排序
  ElMessage.success(`已更新 ${link.name} 的排序值`)
}
</script>

<style lang="less" scoped>
@primary: #4a6cf7;
@secondary: #6c5ce7;
@accent: #ff6b6b;
@light-bg: #f8f9fa;
@text-dark: #333;
@text-light: #666;
@border-color: #e0e0e0;
@card-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
@transition: all 0.3s ease;

.friend-links-container {
  padding: 2rem;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  background-color: #f5f7ff;
  min-height: 100vh;
}

.header {
  text-align: center;
  margin-bottom: 2.5rem;
  
  .title {
    font-size: 2.5rem;
    font-weight: 700;
    color: @text-dark;
    margin-bottom: 0.5rem;
  }
  
  .subtitle {
    font-size: 1.1rem;
    color: @text-light;
  }
}

.control-panel {
  display: flex;
  justify-content: space-between;
  margin-bottom: 1.5rem;
  padding: 1rem;
  background: white;
  border-radius: 8px;
  box-shadow: @card-shadow;
}

.add-btn {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.search-input {
  width: 300px;
}

.links-container {
  background: white;
  border-radius: 8px;
  box-shadow: @card-shadow;
  overflow: hidden;
}

.link-name {
  display: flex;
  align-items: center;
  gap: 0.8rem;
  
  .el-avatar {
    background: @light-bg;
  }
}

.link-url {
  color: @primary;
  text-decoration: none;
  
  &:hover {
    text-decoration: underline;
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 3rem;
  
  .el-empty {
    margin-bottom: 1.5rem;
  }
}

.logo-upload {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.logo-preview {
  width: 120px;
  height: 60px;
  background-size: contain;
  background-position: center;
  background-repeat: no-repeat;
  border-radius: 4px;
  border: 1px dashed @border-color;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f9f9f9;
}

.logo-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: @text-light;
  
  .el-icon {
    font-size: 1.5rem;
    color: #ccc;
    margin-bottom: 0.5rem;
  }
}

.upload-btn {
  width: fit-content;
}

.file-input {
  display: none;
}

/* 操作按钮样式优化 - 确保在同一行 */
.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.action-btn {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  padding: 6px 8px;
  
  .el-icon {
    font-size: 14px;
  }
  
  span {
    font-size: 12px;
  }
}

.el-table {
  .el-button {
    display: flex;
    align-items: center;
    gap: 0.3rem;
  }
}

.el-dialog {
  .el-form-item {
    margin-bottom: 1.5rem;
  }
}
</style>